package com.haiberg.framework.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;


public class FileUploadServlet extends HttpServlet {
	private static final Logger LOG = Logger.getLogger(FileUploadServlet.class);
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		LOG.debug("start upload file...");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			Iterator items;
			try {
				items = upload.parseRequest(request).iterator();
				while (items.hasNext()) {
					FileItem item = (FileItem) items.next();
					if (!item.isFormField()) {
						
						// 取出上传文件的文件名称
						String name = new String(item.getName().getBytes("gbk"), "utf-8");
						String fileName = name.substring(
								name.lastIndexOf('\\') + 1, name.length());
						
						File tempDir = new File(request.getRealPath("file"));
						if(tempDir.isDirectory())
						{
							if(!tempDir.exists())
								tempDir.mkdir();
						}
						
						String path = request.getRealPath("file")
								+ File.separatorChar + fileName;
						// 上传文件
						File uploadedFile = new File(path);
						item.write(uploadedFile);
						// 打印上传成功信息
						response.setContentType("text/html");
						response.setCharacterEncoding("UTF-8");
						PrintWriter out = response.getWriter();
						out.print("<font size='2'>上传的文件为：" + name + "<br>");
						out.print("保存的地址为：" + path + "</font>");
						LOG.debug("upload file success!");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("Error during upload file "+e.getMessage());
			}
		}
		
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}
}